package com.winning.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.constraints.NotNull;
import java.util.Collections;
import java.util.Objects;

/**
 * @Author: xkh@winning.com.cn
 * @Desc: TODO
 * @Date: 2019-01-29 15:01
 **/
@Slf4j
@Validated
@Component
public class ResponseHandler {

    /**
     * 响应处理
     * @param response 请求返回的响应
     * @return 返回响应内容
     */
    public Object handler(@NotNull ResponseEntity response) throws Exception {
        if (Objects.isNull(response)) {
            throw new NullPointerException("参数【ResponseEntity】不能为NULL");
        }

        int status = response.getStatusCodeValue();
        if (200 == status) {
            Object body = response.getBody();
            if (body instanceof String) {
                log.info("响应实体内容["+body+"]");
                JSONObject bjson = JSON.parseObject((String) body);
                return processResult(bjson);
            }

            return response.getBody();
        }

        log.error("请求出现问题：[status:"+response.getStatusCodeValue()+
                "、message："+response.getStatusCode().getReasonPhrase()+"]");

        return Collections.emptyList();
    }

    public static Object processResult(JSONObject bjson) {
        String code = bjson.getString("code");
        String codeDesc = bjson.getString("codeDesc");
        if (code.startsWith("00")) {
            log.info("请求成功：{status："+code+" \ncodeDesc："+codeDesc);
            return bjson.getJSONArray("responseContent");
        }

        log.error("请求失败：{status："+code+" \ncodeDesc："+codeDesc);
        return Collections.emptyList();
    }
}
